package com.example.demo.rabbitmq.consumer;


import com.example.demo.util.ByteUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 implements  Runnable{
    private ConnectionFactory factory;
    private  String queneQNName;
    private String  exchange;
    private String routKey;

    public Consumer1(ConnectionFactory factory, String queneQNName, String exchange, String routKey) {
        this.factory = factory;
        this.queneQNName = queneQNName;
        this.exchange = exchange;
        this.routKey = routKey;
    }
    @Override
    public void run() {
        Connection connection = null;
        try {
            connection =factory.newConnection();
            final Channel channel = connection.createChannel();
            channel.exchangeDeclare(exchange, "topic");
            channel.queueDeclare(queneQNName, true, false, false, null);
            channel.queueBind(queneQNName,exchange,routKey);//队列绑定路由 ，direct发送消息的时候只有路由一木一样才能进行消息路由
            System.out.println("消费者绑定"+exchange+routKey);
            channel.basicQos(1);
            channel.basicConsume(queneQNName, false,
                    new DefaultConsumer(channel) {
                        @Override
                        public void handleDelivery(String consumerTag,
                                                   Envelope envelope,
                                                   AMQP.BasicProperties properties,
                                                   byte[] body)
                                throws IOException {
                            String params = null;
                            try {
                                params =  (String) ByteUtil.getObject(body);
                                System.out.println(routKey+"消费"+params);
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }finally {
                                channel.basicAck(envelope.getDeliveryTag(), false);
                            }
                        }
                    });
        }catch (TimeoutException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
